package com.example.aspect;

/**
 * @Auther: mxt
 * @Date: 2019/9/19 14:10
 * @Description:
 */

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component 
public class LogAspect {
    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);
    @Pointcut("execution(* com.example.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void logbefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        //{}的意思是里面的内容，逗号后面的进行填充
        logger.info("url={}",request.getRequestURI());
        //Method是request的请求方式，get/post
        logger.info("method={}",request.getMethod());
        logger.info("ip={}",request.getRemoteAddr());
        //classMethod调动了哪个类的哪个方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"_"+joinPoint.getSignature().getName());
        //params（args）传递进来什么参数
        logger.info("args={}",joinPoint.getArgs());
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void logAfterReturn(Object object) {
        logger.info("response={}",object);
    }
}
